<!-- 这是搜索的组件 -->
<template>
  <div>
    <span class="go_back"><router-link to='/'><van-icon name="arrow-left" />返回</router-link></span>
    <span class="add_shop"><router-link to='/addShop'>添加</router-link></span>
    <form action="/" style="margin-top: 50px;">
      <van-search
        v-model="inputVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="handleOnSearch"
        @cancel="handleOnCancel"
      />
    </form>
    <!--搜索历史-->
    <div class="search_history" v-show="isShowHistoryList">
      <div class="history_title">
        <span>搜索历史</span>
        <van-icon name="delete" @click="handleDeleteHistory" />
      </div>
      <van-tag v-for="(item, index) in historyKeyword" :key="index" @click="handleClick(item)">{{item}}</van-tag>
      <div class="tips" v-if="historyKeyword.length === 0">
        <span>暂无搜索历史</span>
      </div>
    </div>
    <!--搜索列表-->
    <div class="search_list" v-show="!isShowHistoryList">
      <ul>
        <li v-for="item in searchList" :key="item.id">
          <van-swipe-cell :before-close="beforeClose" @open="handleOpen(item.id)">
            <van-cell :border="false" :title="item.name" :value="'上架时间：' + formatDateTime(item.ctime)" />
            <template #right>
              <van-button square type="danger" text="删除" />
            </template>
          </van-swipe-cell>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputVal: '', // 搜索的关键字
      historyKeyword: [], // 搜素的关键字历史列表
      searchList: [], // 搜索的结果列表
      isShowHistoryList: true, // 历史记录和检索列表切换
      nowItemId: 0 // 当前滑动的选项id
    }
  },
  methods: {
    // Input回车之后获取Input中的值
    handleOnSearch(val) {
      if (!val) {
        this.$toast('请输入搜素的内容！')
        return false
      }
      // 将input框中的值Push到数组中
      this.historyKeyword.push(val)
      // 使用Set去重，然后将Set类型转换为数组
      this.historyKeyword = [...new Set(this.historyKeyword)]
      // 将数组存储到本地localStorage
      localStorage.setItem(
        'historyKeyword',
        JSON.stringify(this.historyKeyword)
      )
      // 回车之后调用接口获取检索的数据
      this.getSearchListData()
    },
    // 点击取消事件
    handleOnCancel() {
      // 清空input框的值
      this.inputVal = ''
      this.isShowHistoryList = true
    },
    // 删除历史记录
    handleDeleteHistory() {
      localStorage.removeItem('historyKeyword')
      this.historyKeyword = []
    },
    // 将历史记录数据点击放到input框中
    handleClick (val) {
      this.inputVal = val
      this.getSearchListData()
    },
    // 获取检索的数据
    async getSearchListData() {
      // 隐藏历史记录，显示搜索列表
      this.isShowHistoryList = false
      // 获取检索数据
      const { data } = await this.$http.get('/api/getprodlist')
      if (data.status !== 0) {
        console.log('接口请求失败')
      }
      this.searchList = data.message
      // console.log(this.searchList)
    },
    // 滑动打开删除
    handleOpen (id) {
      this.nowItemId = id
    },
    // 删除
    beforeClose ({ position, instance }) {
      switch (position) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close()
          break
        case 'right':
          this.$dialog.confirm({
            message: '确定删除吗？'
          }).then(async () => {
            const { data } = await this.$http.get('/api/delproduct/' + this.nowItemId)
            if (data.status !== 0) { this.$toast('删除成功') }
            this.handleOnSearch(this.inputVal)
            instance.close()
          })
          break
      }
    },
    // 时间格式化
    formatDateTime (time) {
      return new Date(+new Date(time) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    }
  },
  mounted() {
    const arr = JSON.parse(localStorage.getItem('historyKeyword'))
    if (arr) {
      this.historyKeyword = arr
    } else {
      this.historyKeyword = []
    }
  }
}
</script>

<style scoped>
.go_back a {
  position: fixed;
  top: 16px;
  left: 10px;
  color: #ffffff;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.add_shop a {
  position: fixed;
  top: 13px;
  right: 10px;
  color: #ffffff;
  font-size: 14px;
  z-index: 999;
}

.search_history {
  padding: 0 10px;
  box-sizing: border-box;
}

.history_title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  padding: 10px 0;
}

.van-tag {
  font-size: 12px;
  padding: 2px 4px;
  margin-right: 8px;
}

.tips {
  width: 100%;
  border-bottom: 1px solid #eeeeee;
  position: relative;
  margin-top: 40px;
}

.tips span {
  position: absolute;
  background: #ffffff;
  padding: 0 15px;
  position: absolute;
  left: 50%;
  top: -10px;
  transform: translateX(-50%);
  font-size: 14px;
  color: #666;
}

.search_list {
  padding: 0 10px;
}

.search_list li {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
  font-size: 14px;
  border-bottom: 1px solid #123;
}

.search_list li :first-child {
  color: #323233;
}

.search_list li :last-child {
  color: #969799;
}

.van-swipe-cell {
  width: 100%;
}

.van-cell__value {
  min-width: 250px;
}

.van-button .van-button__text {
  color: #ffffff !important;
}

.van-cell {
  background: none;
}
</style>
